<template>
  <div id="amapcontainer"></div>
</template>
 
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { listPatrolTrack } from '../../../api/index';
import GPS from '../../../utils/gpstoGD';
let amp = null;
export default {
  props: {
    query: {
      default: () => ({})
    }
  },
  data() {
    return {
      center: [108.478935, 34.997761],
      lineArr: [
        [108.478935, 34.997761],
        [108.478934, 34.997825],
        [108.478912, 34.998549],
        [108.478912, 34.998549],
        [108.478998, 34.998555],
        [108.478998, 34.998555],
        [108.479282, 34.99856],
        [108.479658, 34.998528],
        [108.480151, 34.998453],
        [108.480784, 34.998302],
        [108.480784, 34.998302],
        [108.481149, 34.998184],
        [108.481573, 34.997997],
        [108.481863, 34.997846],
        [108.482072, 34.997718],
        [108.482362, 34.997718],
        [108.483633, 34.998935],
        [108.48367, 34.998968],
        [108.484648, 34.999861]
      ], // 轨迹
      map: null,
      marker: null,
      polyline: null,
      passedPolyline: null,
      markers: [],
      speed: '1倍速',
      duration: 500, // 轨迹回放时间
      percentage: 50 // 进度条进度
    };
  },
  mounted() {
    this.getData(this.query);
  },
  methods: {
    initAMap() {
      AMapLoader.reset();
      AMapLoader.load({
        key: '9e005a1a3c0301babc2e71f27a686fad', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MapType', 'AMap.MoveAnimation'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          const mark = GPS.gcj_encrypt(Number(this.center[1]), Number(this.center[0]));
          const center = this.lineArr.length ? [mark.lon, mark.lat] : this.center;
          // 获取到作为地图容器的DOM元素，创建地图实例
          this.map = new AMap.Map('amapcontainer', {
            //设置地图容器id
            resizeEnable: true,
            viewMode: '3D', // 使用3D视图
            zoomEnable: true, // 地图是否可缩放，默认值为true
            dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
            doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
            zoom: 18, //初始化地图级别
            center: center // 初始化中心点坐标
          });
          this.map.addControl(new AMap.MapType());
        })
        .catch((e) => {
          console.log(e);
        });
    },
    draw() {
      if (this.markers.length) {
        this.markers.forEach((item) => {
          this.map.remove(item);
        });
        this.markers = [];
      }
      AMapLoader.load({ key: '9e005a1a3c0301babc2e71f27a686fad' }).then((AMap) => {
        // this.lineArr = [...this.lineArr].map((item) => [item.longitude, item.latitude]);
        //坐标系转换
        for (let i = 0; i < this.lineArr.length; i++) {
          const Arr = this.lineArr[i];
          const mark = GPS.gcj_encrypt(Number(Arr[1]), Number(Arr[0]));
          this.lineArr[i] = [mark.lon, mark.lat];
        }
        this.marker = new AMap.Marker({
          map: this.map,
          position: this.lineArr[0],
          //offset: new AMap.Pixel(0, 0),
          offset: new AMap.Pixel(-13, -26),
          icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png'
        });

        // 起始点
        let startIcon = new AMap.Icon({
          size: new AMap.Size(25, 34),
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
          imageSize: new AMap.Size(135, 40),
          imageOffset: new AMap.Pixel(-9, -3)
        });
        // 将 起始icon 传入 起始marker
        this.markers[0] = new AMap.Marker({
          position: this.lineArr[0],
          icon: startIcon,
          offset: new AMap.Pixel(-13, -30)
        });
        if (this.lineArr.length > 1) {
          // 终点
          let endIcon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.Size(135, 40),
            imageOffset: new AMap.Pixel(-95, -3)
          });
          // 将 终点icon 传入 终点marker
          this.markers[1] = new AMap.Marker({
            position: this.lineArr[this.lineArr.length - 1],
            icon: endIcon,
            offset: new AMap.Pixel(-13, -30)
          });
        }
        // 将所有 markers 添加到地图
        this.map.add(this.markers);
        // 绘制轨迹
        let polyline = new AMap.Polyline({
          map: this.map,
          path: this.lineArr,
          showDir: true,
          strokeColor: '#28F', //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6, //线宽
          lineJoin: 'round'
          // strokeStyle: "solid"  //线样式
        });

        let passedPolyline = new AMap.Polyline({
          map: this.map,
          // path: this.lineArr,
          strokeColor: '#AF5', //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6 //线宽
          // strokeStyle: "solid"  //线样式
        });

        this.marker.on('moving', function (e) {
          passedPolyline.setPath(e.passedPath);
        });

        this.map.setFitView();
        this.polyline = polyline;
        this.passedPolyline = passedPolyline;
        this.startAnimation();
      });
    },
    startAnimation() {
      if (this.lineArr.length > 1) {
        this.marker.moveAlong(this.lineArr, {
          duration: this.duration,
          autoRotation: false
        });
      } else {
        console.log('请设置多个坐标');
      }
    },
    pauseAnimation() {
      this.marker.pauseMove();
    },
    resumeAnimation() {
      this.marker.resumeMove();
    },
    stopAnimation() {
      this.marker.stopMove();
    },
    clearAnimation() {
      // 起点删除
      if (this.marker) {
        this.marker.stopMove();
        this.marker.setMap(null);
        this.marker = null;
      }
      // 折线删除
      if (this.polyline) {
        this.polyline.setMap(null);
        this.polyline = null;
      }
      // 走过的折线删除
      if (this.passedPolyline) {
        this.passedPolyline.setMap(null);
        this.passedPolyline = null;
      }
    },
    getData(row) {
      //查询巡检记录明细和列表查询巡检坐标点位
      let data = {
        recordNo: row.recordNo
      };
      let arr = [];
      listPatrolTrack(data).then((res) => {
        const _data = res.object.sort((a, b) => a.sort - b.sort);
        for (let i = 0; i < _data.length; i++) {
          let obj = [Number(_data[i].longitude), Number(_data[i].latitude)];
          arr.push(obj);
        }
        this.lineArr = arr;
        this.initAMap(); // 初始化地图
        this.draw();
      });
    },
    // 倍速控制
    handleSelect(e) {
      console.log('e', parseInt(e.charAt(0)));
      this.duration = 500 / parseInt(e.charAt(0));
    }
  },
  unmounted() {
    if (this.map) {
      this.clearAnimation();
    }
  }
};
</script>
 
<style scoped>
#amapcontainer {
  width: 100%;
  height: 100%;
  background-color: palegoldenrod;
}
</style>